package com.lou1052.redis.jedis.action.script;

import com.google.common.collect.Lists;
import com.lou1052.redis.jedis.api.ScriptCommands;
import redis.clients.jedis.Jedis;

import java.util.List;

/**
 * 比较并替换操作 成功返回1  key不存在或者旧值不匹配返回0
 * Created with IntelliJ IDEA.
 * User: liuqing
 * Date: 2015/11/14
 * Time: 20:45
 * To change this template use File | Settings | File Templates.
 */
public class ReplaceObjectAction extends ScriptAction<Boolean> {

    //cas 成功返回1  key不存在或者旧值不匹配返回0
    private static final String CAS_SCRIPT = "if redis.call('get', KEYS[1]) == ARGV[1] then redis.call('set', KEYS[1], ARGV[2]); return 1; else return 0; end";

    private final Object oldValue;

    private final Object newValue;

    public ReplaceObjectAction(String key, Object oldValue, Object newValue) {
        super(key);
        this.oldValue=oldValue;
        this.newValue=newValue;
    }


    @Override
    public Boolean callOn(ScriptCommands scriptCommands) {
        List<Object> params = Lists.newArrayList(oldValue,newValue);
        Long result= (Long)scriptCommands.eval(CAS_SCRIPT,getKey(),params);
        return result>0;
    }
}
